<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;
use \Exception;

class ZlActivePrizeRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_active_prize_record';

    protected $cacheModel = 'prize.user_prize_record';

    /**
     * 写入抽奖记录 list缓存 type=>1未使用 2已使用
     * @param int $uid
     * @param int $activeId
     * @param array $data
     * @return bool
     */
    public function saveData(int $uid, int $activeId, array $data): bool
    {
        try
        {
            $this->save($data);

            CacheManage::getInstance()
                ->setCacheConfig($this->cacheModel, $uid . ':' . $activeId)
                ->listAdd([$this->id => $this->id], 1);
        }
        catch (Exception $e)
        {
            Log::write("写入用户抽奖记录失败；用户ID【{$uid}】活动ID【{$activeId}】更新数据【" . \GuzzleHttp\json_encode($data, JSON_UNESCAPED_UNICODE) . "】;错误信息: . {$e->getMessage()}；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return false;
        }
        return true;
    }


    /**
     * 获取用户中奖的奖品数量
     * @param int $uid
     * @param int $activeId
     * @return array|bool|mixed|string
     * @throws Exception
     */
    public function getUserPrizerNumCount(int $uid, int $activeId)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('prizr_id_count', $uid . ':' . $activeId)->getDataAndSet(function () use ($uid, $activeId)
        {
            try
            {
                $data = $this->where(['active_id' => $activeId, 'prize_type' => 1, 'uid' => $uid])->group('prize_id')->column('count(id)', 'prize_id');
            }
            catch (Exception $e)
            {
                $data = [];
                Log::write("获取用户中奖次数统计失败；活动ID：{$activeId}用户ID：{$uid}【普通抽奖】;错误信息: . {$e->getMessage()}；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            }

            return $data;
        }, [], 'prizr_id_count');
    }

    /**
     * 获取中奖次数统计
     * @param int $activeId
     * @return array|bool|mixed|string
     * @throws Exception
     */
    public function getPrizerNumCount(int $activeId)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('prizr_id_count', $activeId)->getDataAndSet(function () use ($activeId)
        {
            try
            {
                $data = $this->where(['active_id' => $activeId, 'prize_type' => 1])->group('prize_id')->column('count(id)', 'prize_id');
            }
            catch (Exception $e)
            {
                $data = [];
                Log::write("获取中奖次数统计失败；活动ID：{$activeId}【普通抽奖】;错误信息: . {$e->getMessage()}；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            }

            return $data;
        }, [], 'prizr_id_count');
    }

    /**
     * 奖品ID 总奖品品类中奖次数增加 及 用户奖品品类中奖次数增加
     * @param int $uid
     * @param int $activeId
     * @param int $prizeId
     * @param int $max
     * @return bool
     * @throws Exception
     */
    public function prizerNumCountInc(int $uid, int $activeId, int $prizeId, int $max = 0): bool
    {
        $cacheModel = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('prizr_id_count', $activeId);

        $resNum = $cacheModel->setCacheInc($prizeId, 'prizr_id_count', 1); // 更新(所有用户)奖品品类中奖次数增加

        if ($max > 0 && $resNum >= $max)
        {
            $cacheModel->setCacheInc($prizeId, 'prizr_id_count', -1);

            return false;
        }

        CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('prizr_id_count', $uid . ':' . $activeId)->setCacheInc($prizeId, 'prizr_id_count', 1); // 更新当前用户奖品品类中奖次数增加

        return true;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                [$uid, $activeId] = explode(':', $type[0]);
                $this->where(['active_id' => $activeId, 'uid' => $uid]);
            }

            $data = $this->order('id ' . $sortType)->column('uid,active_id,attr,cid,prize_name,prize_id,prize_type,create_time', 'id');
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 未开启缓存从数据库获取分页数据
     * @param array $type 分页数据状态
     * @param string $sortType 排序方式
     * @return array
     */
    public function getPaginateInData($type, $sortType)
    {
        try
        {
            [$uid, $activeId] = explode(':', $type[0]);

            $data = $this->where(['active_id' => $activeId, 'uid' => $uid])->order('id ' . $sortType)
                ->field('id,uid,active_id,attr,cid,prize_name,prize_id,prize_type,create_time')
                ->paginate()->toArray();
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }


    /**
     * 获取抽奖记录列表
     * @param int $uid
     * @param int $activeId
     * @return array|mixed
     * @throws Exception
     */
    public function getRecordList(int $uid, int $activeId)
    {
        $recordList = $this->getListPage($uid . ':' . $activeId, 'id', [], 1, 'desc', 0);

        if ($recordList['data'])
        {
            $taskConfig = config('boxactive.' . $activeId);

            $cids = array_values(array_filter(array_column($recordList['data'], 'cid')));
            $userCouponModel = new UserCoupon();
            $couponListInfo = $userCouponModel->batchGetInfoByIds($cids, ['status', 'end_time', 'use_range']);

            $resData = [];
            foreach ($recordList['data'] as $recordItem)
            {
                if ($recordItem['cid'] > 0 && !isset($couponListInfo[$recordItem['cid']]))
                {
                    try
                    {
                        $couponListInfo[$recordItem['cid']] = $userCouponModel::withTrashed()->alias('uc')->join('wechat_backup_07_18_14_43_00.zl_coupon_attr ca', 'ca.id=uc.c_id')
                            ->where('uc.id', $recordItem['cid'])
                            ->field('ca.use_range,uc.end_time,uc.status,uc.delete_time')->findOrFail()->toArray();

                        if ($couponListInfo[$recordItem['cid']]['delete_time'])
                        {
                            $couponListInfo[$recordItem['cid']]['status'] = 4;
                        }
                    }
                    catch (Exception $e)
                    {
                        continue;
                    }
                }

                if ($recordItem['cid'] > 0 && isset($userCouponModel->goodsTypeTLinkConfig[$couponListInfo[$recordItem['cid']]['use_range']]))
                {
                    $targetData = $userCouponModel->goodsTypeTLinkConfig[$couponListInfo[$recordItem['cid']]['use_range']];

                    (new Goods())->goodsTargetLink((int)$couponListInfo[$recordItem['cid']]['use_range'], $targetData['link']);
                } else
                {
                    $targetData = [
                        'target' => 'local',
                        'link' => 'empty'
                    ];
                }

                $resData[] = [
                    'id' => (int)$recordItem['id'],
                    'title' => $recordItem['cid'] > 0 ? "【{$taskConfig['flags'][$recordItem['attr']]}】{$recordItem['prize_name']}" : "【{$taskConfig['flags'][$recordItem['attr']]}】空盒",
                    'target' => $recordItem['cid'] > 0 ? $targetData['target'] : '',
                    'link' => $recordItem['cid'] > 0 ? $targetData['link'] : '',
                    'status' => $recordItem['cid'] > 0 ? (int)$couponListInfo[$recordItem['cid']]['status'] : 2,  //  0未使用 1已使用 2=>去抽奖 4=>已删除
                    'is_empty' => $recordItem['cid'] > 0 ? 0 : 1,
                    'end_time' => $recordItem['cid'] > 0 ? '有效期至：' . date('Y.m.d', $couponListInfo[$recordItem['cid']]['end_time']) : '',
                    'give_time' => '领取时间：' . date('Y.m.d', $recordItem['create_time']),
                ];
            }

            $recordList['data'] = $resData;
        }

        return $recordList;
    }
}
